<template>
  <v-swatches v-model="color" show-fallback fallback-input-type="color" swatches="text-advanced" style="width: 100%">
    <template #trigger>
      <a-input v-model:value="color" readOnly placeholder="请选择颜色">
        <div slot="suffix" :style="{ width: '1.5em', height: '1.5em', background: color }" />
      </a-input>
    </template>
  </v-swatches>
</template>

<script>
import VSwatches from 'vue3-swatches';
import 'vue3-swatches/dist/style.css';

export default {
  name: 'ColorPicker',
  components: { VSwatches },
  props: {
    modelValue: String,
  },
  data() {
    return {
      color: '',
    };
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(value) {
        if (this.color !== value) {
          this.color = value;
        }
      },
    },
    color: {
      immediate: false,
      handler() {
        if (this.value !== this.color) {
          this.$emit('update:modelValue', this.color);
          setTimeout(() => {
            this.$emit('change', this.color);
          }, 0);
        }
      },
    },
  },
};
</script>

<style lang="less">
.vue-swatches {
  .vue-swatches__trigger__wrapper {
    width: 100%;
  }
  .vue-swatches__container {
    line-height: 1;
    .vue-swatches__fallback__wrapper {
      .vue-swatches__fallback__button {
        margin-top: 3px;
        vertical-align: middle;
      }
    }
  }
}
</style>
